/**
 * ======================
 * storage file
 * =======================
 *
 * The function  about Storage is defined here
 */

export const saveToLocal = (key, value) => {
  localStorage.setItem(key, value)
}

/**
* 存储数据有效期
* id为url参数，key是需要存储数据的键名，val为存储的值
*/
export const saveToExpLocal = (key, value) => {
  const curTime = new Date().getTime()
  localStorage.setItem(key, JSON.stringify({ data: value, time: curTime }))
}

export const getExpLocal = (key, exp) => {
  const data = localStorage.getItem(key)
  const dataObj = JSON.parse(data)
  const expDay = exp * 24 * 3600 * 1000
  if (dataObj) {
    if (new Date().getTime() - dataObj.time > expDay) {
      this.removeItem(key)
      return ''
    } else {
      return dataObj.data
    }
  } else {
    return data || ''
  }
}

/**
* 读取localStorage数据
* def为默认读取数据
*/
export const loadFromLocal = (key, def) => {
  const res = localStorage.getItem(key)
  if (!res) {
    return def
  }
  return res || def
}

/**
 * 清除localstorage
 */
export const removeItem = (key) => {
  localStorage.removeItem(key)
}
export const clearLocal = (key) => {
  localStorage.clear(key)
}

/**
 * sessionStorage存储
 */
export const saveToSession = (key, value) => {
  sessionStorage.setItem(key, JSON.stringify(value))
}

export const getSession = (key, def) => {
  const res = JSON.parse(sessionStorage.getItem(key))
  if (!res) {
    return def
  }
  return res || def
}

export const removeSession = (key) => {
  sessionStorage.removeItem(key)
}

// sessionStorage
export const session = function(key, value) {
  if (value === void (0)) {
    var lsVal = sessionStorage.getItem(key)
    if (lsVal && lsVal.indexOf('autostringify-') === 0) {
      return JSON.parse(lsVal.split('autostringify-')[1])
    } else {
      return lsVal
    }
  } else {
    if (typeof (value) === 'object' || Array.isArray(value)) {
      value = 'autostringify-' + JSON.stringify(value)
    }
    return sessionStorage.setItem(key, value)
  }
}
